import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import useAuthStore from '@/store/auth'
import pinia from '@/store'

const authStore = useAuthStore(pinia)

// routes[0].children = authStore.menuList
const router = createRouter({
  history: createWebHistory('/admin'),

  routes: routes,

  // 切换路由，滚动条移到顶部
  scrollBehavior () {
    return { left: 0, top: 0 }
  },
})

router.beforeEach(async (to, _, next) => {
  // 已登录
  if (authStore.isLogin()) {
    // 加载用户信息
    if (!authStore.username) {
      try {
        await authStore.getUserInfo()
        setTimeout(() => {
          routes[0].children = authStore.menuList
          router.routes = routes
          console.log('router.routes', router.routes)

          // var val = 0
          // for (const item of router.routes[0].children) {
          //   for (const items of item.children) {
          //     if (items.path == to.path) {
          //       val++
          //     }
          //   }
          // }
          // if (!val) {
          //   return next({
          //     path: '/:pathMatch(.*)*',
          //   })
          // }
        }, 100);
      } catch (_) {
        authStore.logout()
        return next({
          path: '/login',
          query: { redirect: to.path == '/' ? undefined : to.path },
        })
      }
    }

    // 未登录
  } else {
    if (!to.meta.guest) {
      return next({
        path: '/login',
        query: { redirect: to.path == '/' ? undefined : to.path },
      })
    }
  }

  return next()
})

export default router
